/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.h2o3.carmack.message;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.h2o3.carmack.session.Session;

/**
 * @author chensheng
 * @version $Id: MessageDispatcher.java, v 0.1 11/30/13 6:13 PM chensheng Exp $
 */
public class MessageDispatcher {
    private static final Logger         logger     = LoggerFactory
                                                       .getLogger(MessageDispatcher.class);

    private Map<String, MessageHandler> handlerMap = Maps.newConcurrentMap();

    public void registerHandler(String code, MessageHandler handler) {
        Preconditions.checkArgument(handler != null, "不能注册空处理器");
        Preconditions.checkArgument(code != null, "代码为空，注册消息处理器失败");

        logger.info("正在注册消息处理器, code=" + code);

        handlerMap.put(code, handler);
    }

    public void dispatch(Session session, Message message) {
        Preconditions.checkArgument(message != null, "分发的消息为空，错误！");

        String code = message.getCode();

        Preconditions.checkArgument(!Strings.isNullOrEmpty(code), "消息 code 为空，分发消息错误");

        MessageHandler handler = handlerMap.get(code);

        if (handler == null) {
            logger.info("没有找到消息处理器，消息代码为:" + code);
        } else {
            handler.handle(session, message);
        }
    }
}
